package com.hncgy.xzf.jdapi.service.product.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hncgy.xzf.jdapi.domain.product.po.PromotionProducts;
import com.hncgy.xzf.jdapi.domain.product.vo.SeckillPromotionVO;
import com.hncgy.xzf.jdapi.mapper.product.PromotionProductsMapper;
import com.hncgy.xzf.jdapi.service.product.IPromotionProductsService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;



/**
 * <p>
 * 秒杀商品关联表 服务实现类
 * </p>
 *
 * @author 不会代码的蜡笔
 * @since 2025-11-04
 */
@Service
public class PromotionProductsServiceImpl extends ServiceImpl<PromotionProductsMapper, PromotionProducts> implements IPromotionProductsService {

    @Override
    public List<SeckillPromotionVO> selectTodaySeckillPromotions(){
        Date now = new Date();
        List<SeckillPromotionVO> data = baseMapper.selectTodaySeckillPromotions();
        data.forEach(item -> {
            //计算活动时间
            if (item.getStartTime() != null && item.getEndTime() != null) {
                if (now.before(item.getStartTime())) {
                    // 活动未开始
                    long diffMillis = item.getStartTime().getTime() - now.getTime();
                    item.setSeckillTime("距开始 " + formatTimeHMS(diffMillis));
                }else {
                    // 活动进行中
                    long diffMillis = item.getEndTime().getTime() - now.getTime();
                    item.setSeckillTime("距结束 " + formatTimeHMS(diffMillis));
                }
            }
            //计算折扣
            item.getProducts().forEach(product -> {
                BigDecimal discount = product.getOriginalPrice().subtract(product.getSeckillPrice())
                        .multiply(BigDecimal.valueOf(100))
                        .divide(product.getOriginalPrice(), 2, BigDecimal.ROUND_HALF_UP);
                product.setDiscount(discount.intValue());
            });
        });
        return data;
    }

    private String formatTimeHMS(long diffMillis) {
        long diffSeconds = Math.abs(diffMillis / 1000); // 添加绝对值确保正数
        long hours = diffSeconds / 3600;
        long minutes = (diffSeconds % 3600) / 60;
        long seconds = diffSeconds % 60;
        return String.format("%02d-%02d-%02d", hours, minutes, seconds);
    }

}
